import router from "../routers";
import { TagsViewModule } from "../store";
import { TagView } from "@/framework/tag-view";

/**
 * 尝试添加并跳转到该页面
 * @param view
 */
export async function tryAddViewAndRedirect(view: TagView) {
  await TagsViewModule.tryAddView(view);
  if (view.url !== router.currentRoute.fullPath) {
    await router.replace(view.url).catch(() => {});
  }
}
/** 移除访问过的页面（移除的是tab 标签页） */
export async function removeVisitedView(view: TagView) {
  const index = await TagsViewModule.removeVisitedView(view);

  if (index >= 0) {
    // 判断当前关闭的页面是否正在显示的页面
    if (TagsViewModule.currentView.uuid === view.uuid) {
      // 切换页面
      const nextIndex = index < TagsViewModule.visitedViews.length ? index : index - 1;
      await router.replace(TagsViewModule.visitedViews[nextIndex].url).catch(() => {});
    }
  }
}
/**
 * 刷新当前页面
 */
export async function refreshCurrentView() {
  if (router.currentRoute.name === "iframe") {
    const ifms = document.querySelector(`iframe[src^='${router.currentRoute.params.url}']`) as any;
    if (ifms) {
      if (ifms.timer) {
        clearTimeout(ifms.timer);
      }
      ifms.src = "about:blank";
      ifms.timer = setTimeout(() => {
        ifms.src = router.currentRoute.params.url;
      }, 50);
    }
  } else {
    if (!router.currentRoute.fullPath.startsWith("/redirect/")) {
      if (router.currentRoute.matched.length) {
        // 如果组件返回的是个函数，则应该从options 中取name 值，否则为object 则直接取name 值
        const component = router.currentRoute.matched[0].components.default;
        const componentName = typeof component === "function" ? (component as any).options.name : (component as any).name;

        await TagsViewModule.removeCachedView(componentName);
      }
      console.log(router.currentRoute.fullPath);

      await router.replace({ path: `/redirect${router.currentRoute.fullPath}` }).then(() => {});
    }
  }
}
